<template>
  <div>
    <!--面包屑导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片视图区域-->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-input placeholder="请输入内容" v-model.trim="queryList.query" clearable @clear="getUserList">
              <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
            </el-input>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="grid-content bg-purple">
            <el-button type="primary" @click="AddialogVisible=true">添加按钮</el-button>
          </div>
        </el-col>
      </el-row>
      <!--用户列表区域-->
      <el-table
        border
        stripe
        :data="userList.slice((queryList.pagenum-1)*queryList.pagesize,queryList.pagesize*queryList.pagenum)"
        style="width: 100%">
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="name" label="角色" width="180"></el-table-column>
        <el-table-column prop="username" label="姓名" width="180"></el-table-column>
        <el-table-column prop="create_time" label="用户密码" width="180">
        </el-table-column>
        <el-table-column prop="mg_state" label="状态" width="180">
          <!--通过scope.row可以获取这行所有信息-->
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="warning" icon="el-icon-edit" size="medium"
                       @click="editDialog(scope.row)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="medium" @click="delDialog(scope.row.id)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页区域-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryList.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryList.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total=total>
      </el-pagination>
    </el-card>
    <!--添加用户对话框-->
    <el-dialog
      title="添加用户"
      :visible.sync="AddialogVisible"
      width="50%" @close="addDialogClose">
      <!--内容主体区域-->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="ID" prop="id">
          <el-input v-model="addForm.id"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="name">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="create_time">
          <el-input v-model="addForm.create_time"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="AddialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUser">确 定</el-button>
  </span>
    </el-dialog>
    <!--修改用户对话框-->
    <el-dialog
      title="修改用户"
      :visible.sync="editdialogVisible"
      width="50%" @close="updateDialogClose">
      <el-form :model="updateform" :rules="updateRules" ref="updateRuleRef" label-width="70px">
        <el-form-item label="姓名" prop="username">
          <el-input v-model="updateform.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="ID" prop="id">
          <el-input v-model="updateform.id" disabled></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="create_time">
          <el-input v-model="updateform.create_time"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="updateform.email"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="editdialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="updateInfo">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
  import axios from 'axios'

  export default {
    data() {
      return {
        //获取用户列表
        queryList: {
          query: '',
          pagenum: 1, //当前页码
          pagesize: 2 //每页显示多少条
        },
        //所有用户列表
        userList: [],
        //总数
        total: 0,
        //添加用户对话框
        AddialogVisible: false,
        //修改用户对话框
        editdialogVisible: false,
        //添加用户表单
        addForm: {
          // id:'',
          // name: '',
          // username: '',
          // create_time: '',
          // email: ''
        },
        //更新用户表单
        updateform: {
          id: '',
          username: '',
          create_time: '',
          email: ''
        },

        userIndex: 0,
        //更新后显示内容

        //添加用户规则
        addFormRules: {
          id: [
            {required: true, message: '请输入id号', trigger: 'blur'},
            {min: 1, max: 4, message: '长度在 1 到 4 个字符', trigger: 'blur'}
          ],
          username: [
            {required: true, message: '请输入用户名', trigger: 'blur'},
            {min: 3, max: 6, message: '长度在 3 到 6 个字符', trigger: 'blur'}
          ],
          name: [
            {required: true, message: '请输入角色', trigger: 'blur'},
            {min: 3, max: 6, message: '长度在 3 到 6 个字符', trigger: 'blur'}
          ],
          create_time: [
            {required: true, message: '请输入密码', trigger: 'blur'},
            {min: 8, max: 10, message: '长度在 8 到 10 个字符', trigger: 'blur'}
          ],
          email: [
            {required: true, message: '请输入邮箱', trigger: 'blur'},
            {min: 5, max: 10, message: '长度在 5 到 10 个字符', trigger: 'blur'}
          ],
        },
        //修改用户规则
        updateRules: {
          id: [
            {required: true, message: '请输入id', trigger: 'blur'},
            {min: 1, max: 4, message: '长度在 1 到 4 个字符', trigger: 'blur'}
          ],
          create_time: [
            {required: true, message: '请输入密码', trigger: 'blur'},
            {min: 7, max: 10, message: '长度在 7 到 10 个字符', trigger: 'blur'}
          ],
          email: [
            {required: true, message: '请输入邮箱', trigger: 'blur'},
            {min: 6, max: 10, message: '长度在 6到 10 个字符', trigger: 'blur'}
          ],
        }
      }
    }
    , created() {
      this.getUserList()
    },
    methods: {
      //获取用户列表信息
      async getUserList() {
        const res = await axios.get('http://localhost:3000/users', {params: this.queryList})
        // console.log(res)
        if (res.data.data.meta.status != 200) {
          return this.$message.error("获取信息失败")
        } else {
          this.userList = res.data.data.user
          this.total = res.data.data.totalPage
          this.queryList.pagenum = res.data.data.pagenum
        }

      },
      //每页显示多少条
      handleSizeChange(newSize) {
        // console.log(newSize)
        this.queryList.pagesize = newSize
        this.getUserList()

      },
      //页码值改变
      handleCurrentChange(newPage) {
        this.queryList.pagenum = newPage
      },
      async userStateChange(userInfo) {
        const res = await axios.put(`http://localhost:3000/users/${userInfo.id}/state/${userInfo.mg_state}`)
        if (res.data.meta.status !== 200) {
          //操作失败复原
          userInfo.mg_state = !userInfo.mg_state
          return this.$message.error("更新状态失败")
        } else {
          this.$message.success("更新状态成功")
        }
      },
      //监听添加对话框的关闭事件
      addDialogClose() {
        this.$refs.addFormRef.resetFields()
      },
      //点击添加用户
      addUser() {
        this.$refs.addFormRef.validate(async valid => {
          if (!valid) {
            return
          } else {
            const res = await axios.post("http://localhost:3000/add", {userMsg: this.addForm})
            if (res.data.meta.status !== 200) {
              return this.$message.error("添加用户失败")
            } else {
              this.$message.success("添加用户成功")
              this.getUserList()
              this.AddialogVisible = false
            }
          }
        })
      },
      //同步对话框信息
      async editDialog(id) {
        const res = await axios.post(`http://localhost:3000/upUser`, {params: id})
        if (res.data.meta.status != 200) {
          return this.$message.error("同步信息失败")
        } else {
          console.log(res.data.data.id)
          //将相应的数据进行赋值
          this.updateform = res.data.data.id
          this.editdialogVisible = true
        }

      },
      //关闭时修改对话框重置
      updateDialogClose() {
        this.$refs.updateRuleRef.resetFields()
      },
      //修改用户信息
      updateInfo() {
        this.$refs.updateRuleRef.validate(async valid => {
          if (!valid) return
          const res = await axios.put(`http://localhost:3000/update/${this.updateform.id}`, {
            email: this.updateform.email, password: this.updateform.create_time
          })
          if (res.data.meta.status !== 200) {
            return this.$message.error("更新数据失败")
          } else {
            this.getUserList()
            this.$message.success("更新数据成功")
            this.editdialogVisible = false

          }
        })
      },
      //删除用户
      async delDialog(id) {
        const res = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => {
          return err
        })
        // console.log(res)
        if (res !== 'confirm') {
          return this.$message.info("已取消删除")
        } else {
          const res = await axios.delete(`http://localhost:3000/delUser/${id}`)
          console.log(res)
          if (res.data.meta.status != 200) {
            return this.$message.error("删除用户失败")
          } else {
            this.$message.success("删除用户成功")
            this.getUserList()
          }
        }
      },
    }
  }
</script>

<style scoped>

</style>
